package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TeacherServlet
 */
@WebServlet("/teacher")
public class TeacherServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if (method == null || "".equals(method)) {
			method = "findAll";
		}
		switch (method) {
		case "findAll":
			findAll(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "insertTeacher":
			insertTeacher(req, resp);
			break;
		case "selectTeacher":
			selectTeacher(req, resp);
			break;
		case "updateTeacher":
			updateTeacher(req,resp);
            break;
		default:
			break;
		}
		
	}

	private void updateTeacher(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
        req.setCharacterEncoding("utf-8");
		
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String salary = req.getParameter("salary");
		System.out.println("id: " + id);
		System.out.println("name: " + name);
		System.out.println("age: " + age);
		System.out.println("salary: " + salary);
		// 根据id来更新的操作
				Connection connection = null;
				PreparedStatement preparedStatement = null;
				try {
					connection = JDBCUtil.getConnection();
					String sql = "update teacher set name=?,age=?,salary=? where id=?";
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, name);
					preparedStatement.setInt(2, Integer.parseInt(age));
					preparedStatement.setDouble(3, Double.parseDouble(salary));
					preparedStatement.setInt(4, Integer.parseInt(id));
					int count = preparedStatement.executeUpdate();
					if (count == 1) {
						System.out.println("修改成功");
					} else {
						System.out.println("修改失败");
					}
				} catch (SQLException e) {
					e.printStackTrace();
				} finally {
					JDBCUtil.close(connection, preparedStatement, null);
				}
				// 修改完之后，重定向到/Java1912Web/findAllStudent
//				resp.sendRedirect("/Java1912Web/findAllStudent")
				resp.sendRedirect(req.getContextPath() + "/teacher");
	}

	private void selectTeacher(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
        String selectId = req.getParameter("id");
		
		// 根据id查找出这个学生对象
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		Teacher teacher = null;
		try { 
			connection = JDBCUtil.getConnection();
			String sql = "select id,name,age,salary from teacher where id=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, Integer.parseInt(selectId));
			resultSet = preparedStatement.executeQuery();
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				Double salary = resultSet.getDouble("salary");
				teacher = new Teacher(id, name, salary, age);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		req.setAttribute("teacher", teacher);
		req.getRequestDispatcher("/teacher_update.jsp").forward(req, resp);
	}

	private void insertTeacher(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("InsertStudentServlet.service()");
		//解决post传参乱码问题
		req.setCharacterEncoding("UTF-8");
		// http://localhost:8080/Java1912Web/insertStudent?name=zhangsan&age=23&gender=男
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String salary = req.getParameter("salary");
		System.out.println(name);
		System.out.println(age);
		System.out.println(salary);
		
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "INSERT INTO teacher(`name`,age,salary) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setInt(2, Integer.parseInt(age));
			preparedStatement.setDouble(3,Double.parseDouble(salary));
			int count = preparedStatement.executeUpdate();
			if (count == 1) {
				System.out.println("插入成功");
			} else {
				System.out.println("插入失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		// 添加完之后再到查询并展示所有的界面
		resp.sendRedirect(req.getContextPath() + "/teacher");
		System.out.println("重定向");
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("DeleteTeacherServlet.service()");
		// http://localhost:8080/Java1912Web/deleteStudent?id=12
		// ?后面的id是传递的参数
		String id = req.getParameter("id");
		System.out.println("id:" + id);
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "delete from teacher where id=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, Integer.parseInt(id));
			int count = preparedStatement.executeUpdate();
			if (count == 1) {
				System.out.println("删除成功");
			} else {
				System.out.println("删除失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		// 删除完成之后，应该查询所有学生展示，就是请求 /Java1912Web/student
		// resp.sendRedirect("/Java1912Web/student");
		// req.getContextPath() 返回当前项目名字
		resp.sendRedirect(req.getContextPath() + "/teacher");
	}

	private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
System.out.println("TeacherServlet.service()");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		ArrayList<Teacher> list = new ArrayList<Teacher>();
		// 加载驱动
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "select id,name,age,salary from teacher";
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				Double salary = resultSet.getDouble("salary");
				Teacher teacher = new Teacher(id, name, salary, age);
				list.add(teacher);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		for (Teacher teacher : list) {
			System.out.println(teacher);
		}
		
		// 把查询出来的list集合放到req里面
		req.setAttribute("list", list);
		// 然后转发到/teacher_list.jsp这个页面进行展示
     	req.getRequestDispatcher("/teacher_list.jsp").forward(req, resp);
	}
	
	
		
	
}
